package br.com.jk.valealim.cartao;

import br.com.jk.util.RNException;
import br.com.jk.valealim.cartaotipo.*;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.JOptionPane;
import br.com.jk.util.Util;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import net.sf.jasperreports.engine.JRException;

/**
 *
 * @author Camilo
 */
public class CartaoJDialog extends javax.swing.JDialog {

  private static CartaoJDialog cartaoJDialog;
  // Model da tabela
  CartaoTableModel cartaoTM = new CartaoTableModel();
  List<Cartao> lstCartao;
  private Boolean modoConsulta = false;
  private Boolean modoConsultaExt = false;
  public JTextField jtfPesquisaId;
  public JTextField jtfPesquisaCliente;
  public JTextField jtfPesquisaTipoCartao;
  public JTextField jtfPesquisaCartaoNum;
  public JTextField jtfPesquisaCodVerif;
  private int colunaSel;
  private Util.SomenteNumeros docCartao = new Util().new SomenteNumeros();
  private Util.SomenteNumeros docCodVerif = new Util().new SomenteNumeros();

  public static CartaoJDialog getInstance(java.awt.Frame parent, boolean modal) {
    if (cartaoJDialog == null) {
      cartaoJDialog = new CartaoJDialog(parent, modal);
    }
    return cartaoJDialog;
  }

  /**
   * Creates new form CartaoTipoJDialog
   */
  private CartaoJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    setLocationRelativeTo(null);
    jlFiltro.setVisible(false);
    listar();
  }

  public static CartaoJDialog getInstance(java.awt.Frame parent, boolean modal, JTextField id,
          JTextField cliente, JTextField tipo, JTextField numero, JTextField codv) {
    if (cartaoJDialog == null) {
      cartaoJDialog = new CartaoJDialog(parent, modal, id, cliente, tipo, numero, codv);
    }
    return cartaoJDialog;
  }

  private CartaoJDialog(java.awt.Frame parent, boolean modal, JTextField id,
          JTextField cliente, JTextField tipo, JTextField numero, JTextField codv) {
    super(parent, modal);
    this.jtfPesquisaId = id;
    this.jtfPesquisaCliente = cliente;
    this.jtfPesquisaTipoCartao = tipo;
    this.jtfPesquisaCartaoNum = numero;
    this.jtfPesquisaCodVerif = codv;
    this.modoConsultaExt = true;
    initComponents();
    jlFiltro.setVisible(false);
    setLocationRelativeTo(null);
    listar();
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do
   * NOT modify this code. The content of this method is always regenerated by the Form
   * Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    JtbMaster = new javax.swing.JToolBar();
    JbNovo = new javax.swing.JButton();
    JbSalvar = new javax.swing.JButton();
    JbEditar = new javax.swing.JButton();
    JbCancelar = new javax.swing.JButton();
    JbExcluir = new javax.swing.JButton();
    jSeparator2 = new javax.swing.JToolBar.Separator();
    JbPesquisar = new javax.swing.JButton();
    JbRelatorio = new javax.swing.JButton();
    jSeparator1 = new javax.swing.JToolBar.Separator();
    JbRefresh = new javax.swing.JButton();
    jlFiltro = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jtCartao = new javax.swing.JTable();
    jpDados = new javax.swing.JPanel();
    jLabel2 = new javax.swing.JLabel();
    jtfId = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jtfIdTipoCartao = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jtfCartaoNum = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    jtfCliente = new javax.swing.JTextField();
    jtfTipoCartao = new javax.swing.JTextField();
    jLabel12 = new javax.swing.JLabel();
    jtfCodVerif = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Cadastro de Cartões/Clientes");
    setResizable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosed(java.awt.event.WindowEvent evt) {
        formWindowClosed(evt);
      }
    });

    JtbMaster.setRollover(true);

    JbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-new.png"))); // NOI18N
    JbNovo.setToolTipText("Novo Registro");
    JbNovo.setFocusable(false);
    JbNovo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbNovo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbNovo.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbNovoActionPerformed(evt);
      }
    });
    JtbMaster.add(JbNovo);

    JbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-save-hd.png"))); // NOI18N
    JbSalvar.setToolTipText("Salvar Registro");
    JbSalvar.setEnabled(false);
    JbSalvar.setFocusable(false);
    JbSalvar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbSalvar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbSalvar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbSalvarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbSalvar);

    JbEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-edit.png"))); // NOI18N
    JbEditar.setToolTipText("Alterar registro");
    JbEditar.setEnabled(false);
    JbEditar.setFocusable(false);
    JbEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbEditar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbEditarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbEditar);

    JbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/dialog-cancel.png"))); // NOI18N
    JbCancelar.setToolTipText("Cancelar o procedimento");
    JbCancelar.setEnabled(false);
    JbCancelar.setFocusable(false);
    JbCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbCancelar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbCancelarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbCancelar);

    JbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/archive-remove.png"))); // NOI18N
    JbExcluir.setToolTipText("Excluir o registro");
    JbExcluir.setEnabled(false);
    JbExcluir.setFocusable(false);
    JbExcluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbExcluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbExcluir.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbExcluirActionPerformed(evt);
      }
    });
    JtbMaster.add(JbExcluir);
    JtbMaster.add(jSeparator2);

    JbPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/edit-find.png"))); // NOI18N
    JbPesquisar.setToolTipText("PESQUISA. (Space)");
    JbPesquisar.setEnabled(false);
    JbPesquisar.setFocusable(false);
    JbPesquisar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbPesquisar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbPesquisar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbPesquisarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbPesquisar);

    JbRelatorio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/report.png"))); // NOI18N
    JbRelatorio.setToolTipText("Relatórios");
    JbRelatorio.setEnabled(false);
    JbRelatorio.setFocusable(false);
    JbRelatorio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRelatorio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRelatorio.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRelatorioActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRelatorio);
    JtbMaster.add(jSeparator1);

    JbRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-refresh.png"))); // NOI18N
    JbRefresh.setToolTipText("Atualizar registros da lista");
    JbRefresh.setFocusable(false);
    JbRefresh.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRefresh.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRefresh.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRefreshActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRefresh);

    jlFiltro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/task-attempt.png"))); // NOI18N
    jlFiltro.setToolTipText("FILTRO ATIVO. Clique no botão Atualizar para restaurar");
    JtbMaster.add(jlFiltro);

    jtCartao.setModel(cartaoTM);
    jtCartao.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtCartao.getSelectedRow();
        selecionado();
      }
    });

    jtCartao.getColumnModel().getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtCartao.getSelectedColumn();
        selecionado();
      }
    });
    jtCartao.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    jtCartao.getColumnModel().getColumn(CartaoTableModel.COLUMN_COD_ID).setPreferredWidth(50);
    jtCartao.getColumnModel().getColumn(CartaoTableModel.COLUMN_COD_TIPO_CARTAO).setPreferredWidth(80);
    jtCartao.getColumnModel().getColumn(CartaoTableModel.COLUMN_COD_CARTAONUM).setPreferredWidth(130);
    jtCartao.getColumnModel().getColumn(CartaoTableModel.COLUMN_COD_CODVERIF).setPreferredWidth(50);
    jtCartao.getColumnModel().getColumn(CartaoTableModel.COLUMN_COD_CLIENTE).setPreferredWidth(180);
    jtCartao.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        jtCartaoMouseClicked(evt);
      }
    });
    jtCartao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtCartaoKeyPressed(evt);
      }
    });
    jScrollPane1.setViewportView(jtCartao);

    jpDados.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Dados"));

    jLabel2.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel2.setText("Id");

    jtfId.setEditable(false);
    jtfId.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfId.setEnabled(false);

    jLabel1.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel1.setText("Tipo Cartão");

    jtfIdTipoCartao.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdTipoCartao.setEnabled(false);
    jtfIdTipoCartao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdTipoCartaoKeyPressed(evt);
      }
    });

    jLabel3.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel3.setText("Cartão");

    jtfCartaoNum.setDocument(docCartao);
    jtfCartaoNum.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfCartaoNum.setEnabled(false);
    jtfCartaoNum.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfCartaoNumKeyPressed(evt);
      }
    });

    jLabel4.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel4.setText("Nome do Cliente");

    jtfCliente.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfCliente.setEnabled(false);
    jtfCliente.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfClienteFocusLost(evt);
      }
    });
    jtfCliente.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfClienteKeyPressed(evt);
      }
      public void keyReleased(java.awt.event.KeyEvent evt) {
        jtfClienteKeyReleased(evt);
      }
    });

    jtfTipoCartao.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfTipoCartao.setEnabled(false);

    jLabel12.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel12.setText("Cod Verif");

    jtfCodVerif.setDocument(docCodVerif);
    jtfCodVerif.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfCodVerif.setEnabled(false);
    jtfCodVerif.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfCodVerifKeyPressed(evt);
      }
    });

    javax.swing.GroupLayout jpDadosLayout = new javax.swing.GroupLayout(jpDados);
    jpDados.setLayout(jpDadosLayout);
    jpDadosLayout.setHorizontalGroup(
      jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jpDadosLayout.createSequentialGroup()
        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jLabel4)
          .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
            .addComponent(jtfCliente)
            .addGroup(jpDadosLayout.createSequentialGroup()
              .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addGroup(jpDadosLayout.createSequentialGroup()
                  .addComponent(jLabel2)
                  .addGap(35, 35, 35))
                .addGroup(jpDadosLayout.createSequentialGroup()
                  .addComponent(jtfId)
                  .addGap(6, 6, 6)))
              .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jpDadosLayout.createSequentialGroup()
                  .addComponent(jtfIdTipoCartao, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                  .addComponent(jtfTipoCartao, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addComponent(jLabel1))
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jpDadosLayout.createSequentialGroup()
                  .addComponent(jLabel3)
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                  .addComponent(jLabel12))
                .addGroup(jpDadosLayout.createSequentialGroup()
                  .addComponent(jtfCartaoNum, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                  .addComponent(jtfCodVerif, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))))))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    jpDadosLayout.setVerticalGroup(
      jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jpDadosLayout.createSequentialGroup()
        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel2)
          .addComponent(jLabel1)
          .addComponent(jLabel3)
          .addComponent(jLabel12))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jtfId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfIdTipoCartao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfCartaoNum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfTipoCartao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfCodVerif, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(6, 6, 6)
        .addComponent(jLabel4)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jtfCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(JtbMaster, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 510, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addComponent(jpDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(JtbMaster, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jpDados, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void JbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbNovoActionPerformed
    novo();
  }//GEN-LAST:event_JbNovoActionPerformed

  private void JbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbSalvarActionPerformed
    salvar();
  }//GEN-LAST:event_JbSalvarActionPerformed

  private void JbEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbEditarActionPerformed
    editar();
  }//GEN-LAST:event_JbEditarActionPerformed

  private void JbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbCancelarActionPerformed
    cancelar();
  }//GEN-LAST:event_JbCancelarActionPerformed

  private void JbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbExcluirActionPerformed
    excluir();
  }//GEN-LAST:event_JbExcluirActionPerformed

  private void JbPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbPesquisarActionPerformed
    pesquisar();
  }//GEN-LAST:event_JbPesquisarActionPerformed

  private void JbRelatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRelatorioActionPerformed
    try {
      ThreadReport thReport = new ThreadReport();
      thReport.start();
    } catch (Exception e) {
      Util.msgErro(e, "Erro ao gerar o relatório");
    }
  }//GEN-LAST:event_JbRelatorioActionPerformed

  private void JbRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRefreshActionPerformed
    listar();
    jlFiltro.setVisible(false);
    JbPesquisar.setEnabled(false);
  }//GEN-LAST:event_JbRefreshActionPerformed

  private void jtCartaoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtCartaoMouseClicked
    if (cartaoTM.getRowCount() > 0 && (jtfId.getText() != null && jtfCliente != null)) {
      HabilitaJb(true, false, true, false, true);
      HabilitaJtf(false);
      limpar();
      modoConsulta = false;
      selecionado();
    }
  }//GEN-LAST:event_jtCartaoMouseClicked

  private void jtCartaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtCartaoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (modoConsultaExt) {
        this.selecionarRegistro();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
      if (modoConsulta) {
        this.pesquisar();
      }
    }
  }//GEN-LAST:event_jtCartaoKeyPressed

  private void jtfIdTipoCartaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdTipoCartaoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfIdTipoCartao.getText().isEmpty()) {
        consultaCartaoTipo();
      } else {
        jtfCartaoNum.requestFocus();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      consultaCartaoTipo();
    }
  }//GEN-LAST:event_jtfIdTipoCartaoKeyPressed

  private void jtfCartaoNumKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCartaoNumKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfCodVerif.requestFocus();
    }
  }//GEN-LAST:event_jtfCartaoNumKeyPressed

  private void jtfClienteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfClienteKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      this.salvar();
    }
  }//GEN-LAST:event_jtfClienteKeyPressed

  private void jtfCodVerifKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCodVerifKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfCliente.requestFocus();
    }
  }//GEN-LAST:event_jtfCodVerifKeyPressed

  private void jtfClienteFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfClienteFocusLost
    Util.setFirstLetterUpperCase(jtfCliente);
  }//GEN-LAST:event_jtfClienteFocusLost

  private void jtfClienteKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfClienteKeyReleased
    Util.setFirstLetterUpperCase(jtfCliente, jtfCliente.getSelectionStart());
  }//GEN-LAST:event_jtfClienteKeyReleased

  private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    cartaoJDialog = null;
  }//GEN-LAST:event_formWindowClosed

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(CartaoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(CartaoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(CartaoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(CartaoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        CartaoJDialog dialog = new CartaoJDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton JbCancelar;
  private javax.swing.JButton JbEditar;
  private javax.swing.JButton JbExcluir;
  private javax.swing.JButton JbNovo;
  private javax.swing.JButton JbPesquisar;
  private javax.swing.JButton JbRefresh;
  private javax.swing.JButton JbRelatorio;
  private javax.swing.JButton JbSalvar;
  private javax.swing.JToolBar JtbMaster;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel12;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JToolBar.Separator jSeparator1;
  private javax.swing.JToolBar.Separator jSeparator2;
  private javax.swing.JLabel jlFiltro;
  private javax.swing.JPanel jpDados;
  private javax.swing.JTable jtCartao;
  private javax.swing.JTextField jtfCartaoNum;
  private javax.swing.JTextField jtfCliente;
  private javax.swing.JTextField jtfCodVerif;
  private javax.swing.JTextField jtfId;
  private javax.swing.JTextField jtfIdTipoCartao;
  private javax.swing.JTextField jtfTipoCartao;
  // End of variables declaration//GEN-END:variables

  private void setJtCartaoTm(List<Cartao> ct) {
    while (cartaoTM.getRowCount() > 0) {
      cartaoTM.remove(0);
    }
    if (!ct.isEmpty()) {
      cartaoTM.adicionaLista(ct);
    }
  }

  private void setJtCartaoTm(Cartao ct) {
    while (cartaoTM.getRowCount() > 0) {
      cartaoTM.remove(0);
    }
    if (ct != null) {
      cartaoTM.adiciona(ct);
    }
  }

  private void novo() {
    limpar();
    HabilitaJb(false, true, false, true, false);
    HabilitaJtf(true);
    jtfIdTipoCartao.requestFocus();
  }

  private void salvar() {
    try {
      Cartao cartao = criaObjetos();
      CartaoRn ctRn = new CartaoRn();

      //faz a conexão com o bd e salva os registros
      ctRn.salvar(cartao);

      listar();
      HabilitaJb(true, false, false, false, false);
      HabilitaJtf(false);
      limpar();
    } catch (Exception e) {
      Util.msgErro(e, "Ocorreu erro ao tentar gravar no banco de dados");
    }
  }

  private void listar() {
    CartaoRn ctRn = new CartaoRn();
    setJtCartaoTm(lstCartao = ctRn.listar());
  }

  private void limpar() {
    jtfId.setText(null);
    jtfIdTipoCartao.setText(null);
    jtfTipoCartao.setText(null);
    jtfCartaoNum.setText(null);
    jtfCodVerif.setText(null);
    jtfCliente.setText(null);
  }

  /**
   * Determina quais os botões da barra de ferramentas ficará ativo
   *
   * @param novo
   * @param salvar
   * @param editar
   * @param cancelar
   * @param excluir
   */
  private void HabilitaJb(Boolean novo, Boolean salvar, Boolean editar, Boolean cancelar,
          Boolean excluir) {
    JbNovo.setEnabled(novo);
    JbSalvar.setEnabled(salvar);
    JbEditar.setEnabled(editar);
    JbCancelar.setEnabled(cancelar);
    JbExcluir.setEnabled(excluir);
  }

  /**
   * Define se os JTextFields serão liberados para edição do usuário
   *
   * @param tf <b>True</b> - Habilitar; <b>False</b> - Desabilitar;
   */
  private void HabilitaJtf(Boolean tf) {
    jtfIdTipoCartao.setEnabled(tf);
    jtfCartaoNum.setEnabled(tf);
    jtfCodVerif.setEnabled(tf);
    jtfCliente.setEnabled(tf);
  }

  private void selecionado() {
    int linhaSel = jtCartao.getSelectedRow();
//    verifica se há realmente alguma linha selecionada
    if (linhaSel >= 0) {
      int columSel = jtCartao.getSelectedColumn();
      boolean pesq = setEnabledPesquisa(columSel);

      jtfId.setText(this.cartaoTM.getValueAt(linhaSel, CartaoTableModel.COLUMN_COD_ID).toString());
      jtfIdTipoCartao.setText(this.cartaoTM.getValueAt(linhaSel, CartaoTableModel.COLUMN_COD_ID_TIPO_CARTAO).toString());
      jtfTipoCartao.setText(this.cartaoTM.getValueAt(linhaSel, CartaoTableModel.COLUMN_COD_TIPO_CARTAO).toString());
      jtfCartaoNum.setText(this.cartaoTM.getValueAt(linhaSel, CartaoTableModel.COLUMN_COD_CARTAONUM).toString());
      jtfCodVerif.setText(this.cartaoTM.getValueAt(linhaSel, CartaoTableModel.COLUMN_COD_CODVERIF).toString());
      jtfCliente.setText(this.cartaoTM.getValueAt(linhaSel, CartaoTableModel.COLUMN_COD_CLIENTE).toString());

      modoConsulta = pesq;
      JbPesquisar.setEnabled(pesq);
    }
  }

  private void editar() {
    HabilitaJb(false, true, false, true, false);
    HabilitaJtf(true);
    jtfIdTipoCartao.requestFocus();
  }

  private void excluir() {
//    Define os objetos
    CartaoRn ctRn = new CartaoRn();
    Cartao ct = criaObjetos();
//    Executa o procedimento no BD
    ctRn.excluir(ct);

    listar();
    limpar();
  }

  /**
   * Cria instâncias dos objetos para serem enviados para o BD
   *
   * @return
   */
  private Cartao criaObjetos() {
    Cartao c = new Cartao();

    //preenche o objeto com os dados dos jtextfield
    if (!jtfId.getText().isEmpty()) {
      c.setId(Integer.parseInt(jtfId.getText()));
    }
    if (!jtfCodVerif.getText().isEmpty()) {
      c.setCartaoCodVerif(Integer.parseInt(jtfCodVerif.getText()));
    }
    c.setCartaoNumero(jtfCartaoNum.getText());
    c.setNomeCliente(jtfCliente.getText());

    CartaoTipoRn ctrn = new CartaoTipoRn();
    CartaoTipo ct = ctrn.carregar(Integer.parseInt(jtfIdTipoCartao.getText()));
    c.setCartaoTipo(ct);

    return c;
  }

  private void cancelar() {
    limpar();
    HabilitaJb(true, false, false, false, false);
    HabilitaJtf(false);
    if (modoConsulta) {
      modoConsulta = false;
    } else {
      listar();
    }
  }

  private void report() throws JRException, Exception {
    CartaoReport mReport = new CartaoReport();
    mReport.geraRelatorio1();
  }

  private void pesquisar() {
    if (modoConsulta) {
      String criterio = JOptionPane.showInputDialog(null, "Digite o critério da pesquisa:",
              "Pesquisa", JOptionPane.INFORMATION_MESSAGE);
      if (criterio == null || criterio.isEmpty()) {
        JbPesquisar.setEnabled(false);
      } else {
        limpar();

        CartaoRn ctrn = new CartaoRn();
//        Verifica qual é o tipo de campo e executa a consulta específica

        switch (colunaSel) {
          case CartaoTableModel.COLUMN_COD_ID:
            try {
              setJtCartaoTm(ctrn.carregar(Integer.parseInt(criterio)));
            } catch (RNException e) {
              Util.msgErro(e, "");
            }
            break;
          case CartaoTableModel.COLUMN_COD_TIPO_CARTAO:
            setJtCartaoTm(ctrn.pesquisaPadrao(CartaoDaoHibernate.PROPERTY_TIPOCARTAO, criterio));
            break;
          case CartaoTableModel.COLUMN_COD_CARTAONUM:
            setJtCartaoTm(ctrn.pesquisaPadrao(CartaoDaoHibernate.PROPERTY_CARTAONUM, criterio));
            break;
          case CartaoTableModel.COLUMN_COD_CLIENTE:
            int i = Integer.parseInt(criterio);
            setJtCartaoTm(ctrn.pesquisaPadrao(CartaoDaoHibernate.PROPERTY_CLIENTE, i));
            break;
        }
        jlFiltro.setVisible(true);
      }
    }
  }

  private void getLarguraJtBanco() {
    int grade;
    int column = cartaoTM.getColumnCount();
    //JtBanco.getColumnModel().getSelectedColumnCount();
    for (int i = 0; i < column; i++) {
      grade = this.jtCartao.getColumnModel().getColumn(i).getPreferredWidth();
      System.out.println(grade);
    }
  }

  class ThreadReport extends Thread {

    @Override
    public void run() {
      try {
        report();
      } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage());
      }
    }
  }

  public void selecionarRegistro() {
    int linhaSel = jtCartao.getSelectedRow();
    jtfPesquisaId.setText(this.cartaoTM.getValueAt(linhaSel, CartaoTableModel.COLUMN_COD_ID).toString());
    jtfPesquisaCliente.setText(this.cartaoTM.getValueAt(linhaSel, CartaoTableModel.COLUMN_COD_CLIENTE).toString());
    jtfPesquisaCartaoNum.setText(this.cartaoTM.getValueAt(linhaSel, CartaoTableModel.COLUMN_COD_CARTAONUM).toString());
    jtfPesquisaCodVerif.setText(this.cartaoTM.getValueAt(linhaSel, CartaoTableModel.COLUMN_COD_CODVERIF).toString());
    jtfPesquisaTipoCartao.setText(this.cartaoTM.getValueAt(linhaSel, CartaoTableModel.COLUMN_COD_TIPO_CARTAO).toString());
    this.modoConsultaExt = false;
    this.dispose();
  }

  /**
   * Habilita a pesquisa somente para os campos configurados nesse método
   *
   * @param coluna Índice da coluna da qual se deseja efetuar a pesquisa
   * @return Se o campo estiver habilitado permite a pesquisa. O default é: false;
   */
  public boolean setEnabledPesquisa(int coluna) {
    colunaSel = coluna;
    switch (coluna) {
      case CartaoTableModel.COLUMN_COD_ID:
        return true;
      case CartaoTableModel.COLUMN_COD_TIPO_CARTAO:
        return true;
      case CartaoTableModel.COLUMN_COD_CARTAONUM:
        return true;
      case CartaoTableModel.COLUMN_COD_CLIENTE:
        return true;
      default:
        return false;
    }
  }

  public void consultaCartaoTipo() {
    CartaoTipoJDialog.getInstance(null, true, jtfIdTipoCartao, jtfTipoCartao).setVisible(true);
  }
}
